#pragma once
#include "mysql.hpp"
#include "friend_apply.hxx"
#include "friend_apply-odb.hxx"

namespace xchat
{
class FriendApplyTable
{
public:
    using ptr = std::shared_ptr<FriendApplyTable>;

    FriendApplyTable(const std::shared_ptr<odb::core::database>& db) 
        : _db(db) {}

    //新增申请
    bool insert(FriendApply &fapply)
    {
        try
        {
            odb::transaction trans(_db->begin());
            _db->persist(fapply);
            trans.commit();
        }catch(std::exception &e){
            LOG_ERROR("新增好友申请FriendApply失败 {}->{} : {}", fapply.user_id(), fapply.peer_id(), e.what());
            return false;
        }
        return true;
    }
    //bool remove(const std::string &eid){}
    bool remove(const std::string &uid, const std::string &pid)
    {
        try
        {
            odb::transaction trans(_db->begin());
            typedef odb::query<FriendApply> query;
            typedef odb::result<FriendApply> result;
            _db->erase_query<FriendApply>(query::user_id == uid && query::peer_id == pid); 
            trans.commit();
        }
        catch(std::exception &e){
            LOG_ERROR("删除好友申请事件失败 {}-{} : {}",uid, pid, e.what());
            return false;
        }
        return true;
    }
    bool exists(const std::string &uid, const std::string &pid)
    {
        typedef odb::query<FriendApply> query;
        typedef odb::result<FriendApply> result;
        std::shared_ptr<FriendApply> r;
        try
        {
            //开启事务
            odb::transaction trans(_db->begin());
            r = std::shared_ptr<FriendApply>(_db->query_one<FriendApply>(query::user_id == uid && query::peer_id == pid)); 
            //LOG_DEBUG("查询完毕");
            //提交事务
            trans.commit();

        }catch(std::exception &e){
            LOG_ERROR("查找FriendApply失败 {}-{} : {}",uid, pid, e.what());
        }
        return r != nullptr;
    }
    //查询好友申请 看看谁要加我
    std::vector<std::string> apply_users(const std::string &uid) 
    {
        std::vector<std::string> res;
        try
        {
            //开启事务
            odb::transaction trans(_db->begin());
            typedef odb::query<FriendApply> query;
            typedef odb::result<FriendApply> result;
            //传入的uid是被申请者
            result r(_db->query<FriendApply>(query::peer_id == uid));
            for (const auto &it : r)
            {
                res.push_back(it.user_id());
            }
            //提交事务
            trans.commit();

        }catch(std::exception &e){
            LOG_ERROR("通过用户查找好友申请失败{} {}",uid, e.what());
        }
        return res;
    }
private:
    std::shared_ptr<odb::core::database> _db;
};

}